<template>
  <div class="container">
    <div class="sign-in"
         v-bind:style="{'backgroundImage':'url('+logoUrl+')'}">
      <h3>渠道管理分销助手</h3>
      <ul class="sign-list">
        <li>
          <div class="sign-list-row">
            <label class="row-title">帐号</label>
            <div class="row-content">
              <input type="text"
                     placeholder="请输入帐号"
                     v-model="loginData.phone">
              <i class="fa fa-times-circle fa-hidden"></i>
              <i class="fa fa-exclamation-circle"></i>
            </div>
          </div>
        </li>
        <li>
          <div class="sign-list-row">
            <label class="row-title">密码</label>
            <div class="row-content">
              <input type="password"
                     placeholder="请输入密码"
                     v-model="loginData.password">
              <i class="fa fa-times-circle "></i>
            </div>
          </div>
        </li>
        <a href="javascript:void(0)"
           @click="toForgetPassword"
           style="color:#666;float: right;text-decoration: underline;">忘记密码</a>
      </ul>
      <button class="btn btn-sign"
              @click="loginUser()">登录</button>
      <button class="btn btn-sign"
              style="margin-top: 15px;"
              @click="toRegister()">新用户注册</button>
    </div>
    <div class="version">当前版本：{{version}}</div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      logoUrl: "",
      loginData: {
        phone: "",
        password: "",
        wxOpenId: window.localStorage.getItem("3_wxOpenid"),
        cooCompanyId: ""
      },
      logoInfo: {
        logoType: "1"
      },
      companyList: [],
      version: "11.1.01"
    };
  },
  mounted: function () {
    //if(!window.localStorage.getItem("3_wxOpenid")) {
    if (!this.getQueryString("companyUuid")) {
      this.getCompanyLogo();
      this.autoLogin();
    } else if (this.getQueryString("openId")) {
      window.localStorage.setItem("3_wxOpenid", this.getQueryString("openId")),
        this.getCompanyLogo();
      this.autoLogin();
    } else {
      this.wxAuth();
    }
    // } else {
    //     this.getCompanyLogo();
    //     this.autoLogin();
    // }
  },
  methods: {
    toForgetPassword() {
      this.$router.push({
        path: "/forgetPassword"
      });
    },
    getCompanyLogo: function () {
      var _self = this;
      var url = _self.utilHelper.apiUrl + "/api/getLogo";
      var body = {};
      body.params = _self.logoInfo;
      _self.$http.post(url, body).then((response) => {
        var data = response.body.resData;
        if (data.result == "1") {
          _self.logoUrl = data.logoUrl;
        } else {
          var pathName = window.document.location.pathname;
          var projectName = pathName.substring(
            0,
            pathName.substr(1).indexOf("/") + 1
          );
          _self.logoUrl = projectName + "/src/assets/images/logo.png";
        }
      });
    },
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return unescape(r[2]);
      }
      return null;
    },
    wxAuth() {
      var url = this.utilHelper.apiUrl + "/weixin/getWxConfig";
      this.$http.post(url, null).then((response) => {
        var body = response.body;
        if (body.code == "success") {
          this.gotoWeiXinAuth(body.appId, body.companyUuid);
        } else if (body.code == "fail") {
          //没有配置微信授权路径
          this.getCompanyLogo();
          this.autoLogin();
        } else {
          console.log(body);
        }
      });
    },
    //微信静默授权请求
    gotoWeiXinAuth(appId, companyUuid) {
      let systemId = "3";
      var state =
        companyUuid +
        "|" +
        window.location.hostname +
        "|" +
        encodeURIComponent(window.location.pathname) +
        "|login|" +
        systemId;
      let redirect_uri = this.utilHelper.apiUrl + "/weixin/getWeiXinAuth";
      if (this.$route.query.redirectUrl) {
        redirect_uri += "?bus_uri=" + this.$route.query.redirectUrl;
      }
      var weixinUrl =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appId +
        "&redirect_uri=" +
        encodeURIComponent(redirect_uri) +
        "&response_type=code&scope=snsapi_base&state=" +
        state +
        "&connect_redirect=1#wechat_redirect";
      window.location.href = weixinUrl;
    },
    loginUser: function () {
      var _self = this;
      if (_self.vaild()) {
        var body = {};
        body.params = _self.loginData;
        body.params.wxOpenId =
          this.getQueryString("openId") ||
          window.localStorage.getItem("3_wxOpenid");
        var url = _self.utilHelper.apiUrl + "/api/login";
        _self.$http.post(url, body).then(
          (response) => {
            var data = response.body.resData;
            var result = data.result;
            var errorMsg = data.resultMsg;
            if (result == "1") {
              window.localStorage.setItem("3_userId", data.id);
              window.localStorage.setItem("3_userName", data.accountName);
              window.localStorage.setItem(
                "3_password",
                _self.loginData.password
              );
              window.localStorage.setItem("3_phone", data.phone);
              window.localStorage.setItem("3_isLogin", true);
              window.localStorage.setItem("3_userRole", data.userRoleId);
              window.localStorage.setItem("3_accountType", data.accountType);
              if (_self.$route.query.redirectUrl) {
                _self.$router.replace({
                  path: _self.$route.query.redirectUrl
                });
              } else {
                _self.$router.replace({
                  path: "/index"
                });
              }
            } else {
              layer.msg(errorMsg, {
                time: 1000
              });
            }
          },
          (response) => {
            layer.msg("登陆超时", {
              time: 1000
            });
          }
        );
      }
    },
    vaild: function () {
      var _self = this;
      if (!_self.loginData.phone) {
        layer.msg("请输入登录帐号", {
          time: 2000
        });
        return false;
      }
      if (!_self.loginData.password) {
        layer.msg("请输入登录密码", {
          time: 2000
        });
        return false;
      }
      return true;
    },
    toRegister() {
      this.$router.push({ path: "/register" });
    },
    autoLogin() {
      console.log("autoLogin");
      var _self = this;
      var phone = window.localStorage.getItem("3_phone");
      var password = window.localStorage.getItem("3_password");
      if (!phone) {
        return;
      }
      if (!password) {
        return;
      }
      var loginData = {};
      loginData.phone = phone;
      loginData.password = password;
      loginData.wxOpenId =
        this.getQueryString("openId") ||
        window.localStorage.getItem("3_wxOpenid");
      if (phone) {
        var body = {};
        body.params = loginData;
        var url = _self.utilHelper.apiUrl + "/api/login";
        _self.$http.post(url, body).then(
          (response) => {
            var data = response.body.resData;
            var result = data.result;
            var errorMsg = data.resultMsg;
            if (result == "1") {
              window.localStorage.setItem("3_userId", data.id);
              window.localStorage.setItem("3_userName", data.accountName);
              window.localStorage.setItem(
                "3_password",
                _self.loginData.password
              );
              window.localStorage.setItem("3_phone", data.phone);
              window.localStorage.setItem("3_isLogin", true);
              window.localStorage.setItem("3_userRole", data.userRoleId);
              window.localStorage.setItem("3_accountType", data.accountType);
              if (_self.$route.query.redirectUrl) {
                _self.$router.replace({
                  path: _self.$route.query.redirectUrl
                });
              } else {
                _self.$router.replace({
                  path: "/index"
                });
              }
            } else {
              layer.msg(errorMsg, {
                time: 1000
              });
            }
          },
          (response) => {
            // layer.msg('登陆超时', {
            //     time: 1000
            // });
          }
        );
      }
    }
  }
};
</script>
<style scoped>
.version {
  position: fixed;
  bottom: 60px;
  right: 20px;
}
.row-title {
  text-align: right;
  padding-right: 10px;
}
.row-content input {
  padding-left: 8px;
}
.row-select {
  height: 24px;
  line-height: 24px;
  width: 200px;
  background-color: #f2f2f2;
  padding-left: 8px;
  padding-right: 20px;
}
.row-content .fa-angle-down {
  position: absolute;
  right: 8px;
  top: 2px;
  display: block;
}
.sign-in1 {
  padding: 130px 20px 50px;
  background: url({{logoUrl}}) no-repeat center 100px;
  background-size: 83px auto;
  height: 100%;
}
</style>